package com.weiaibenpao.demo.chislim.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.weiaibenpao.demo.chislim.Interface.OnGetPro;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.adater.RecyclerUserPicAdapter;
import com.weiaibenpao.demo.chislim.base.BaseFragment;
import com.weiaibenpao.demo.chislim.bean.Li_UserInfoResult;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.model.MyModel;
import com.weiaibenpao.demo.chislim.ui.Li_Medal_Activity;
import com.weiaibenpao.demo.chislim.ui.SetActivity;
import com.weiaibenpao.demo.chislim.ui.UpdateUserActivity;
import com.weiaibenpao.demo.chislim.util.ACache;
import com.weiaibenpao.demo.chislim.util.CircleTransform;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by Administrator on 2016/4/22.
 */
public class UserFragment extends BaseFragment implements View.OnClickListener {

    private TextView getStart;
    /*界面控件*/
    public  TextView userIntro;         ///用户个性签名
    private ImageView userImage;        //用户头像
    private ImageView userSetIcon;      //用户信息编辑
    private TextView userName;          //用户名称*/
    private ImageView userSet;          //用户设置
    private TextView updateUser;        //修改用户信息
    private TextView userHeight;        //用户身高
    private TextView userWeight;        //用户体重
    private TextView userBMI;           //用户的BMI

    private TextView careId;
    private TextView funsId;
    private TextView dynamicsId;

    private ImageView gradeProgressd;
    private ImageView gradeProgress;

    private LinearLayout sportSucces;
    private TextView gradePlan;

    private View view;

    private UserBean user;

    Context context;
    ViewGroup.LayoutParams para;

    int width = 0;

    int dis = 0;

    //等级进度条
    private ImageView contentImageView;
    private ImageView overImageView;
    private float h, w;

    DecimalFormat decimalFormat;

    RecyclerUserPicAdapter adapter;
    RecyclerView recyclerView;
    private ACache mCache;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_user, container, false);
        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }

        user = UserBean.getUserBean();
        context = getActivity();
        mCache = ACache.get(context);    //实例化缓存
        initView(view);

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {

        getUserInfo();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(user.userImage == null || user.userImage == ""){

        }else{
            Picasso.with(context)
                    .load(user.userImage)
                    .resize(200, 200)
                    .transform(new CircleTransform())
                    .into(userImage);
        }


   /*     userName.setText(user.userName);*/
        userHeight.setText(String.valueOf(user.userHeigh));
        userWeight.setText(String.valueOf(user.userWeight));
        //float bmi = (float) (user.userWeight/((user.userHeigh*0.01)*(user.userHeigh*0.01)));
         userBMI.setText(String.valueOf(user.userBmi));
        // userBMI.setText(printNum(bmi));
        userIntro.setText(UserBean.getUserBean().userTntru);

        userName.setText(UserBean.getUserBean().userName);
    }

    /**
     * 保留一位小数
     * @param d
     * @return
     */
    private String printNum(double d) {

        if (decimalFormat == null) {
            decimalFormat = new DecimalFormat("0.0");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        }
        decimalFormat.format(d);

        /*BigDecimal bdc = new BigDecimal(d);
        System.out.println(bdc);
        double d1 = bdc.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();*/

        return decimalFormat.format(d);
    }

    @Override
    public void initView(View view) {
        userSetIcon = (ImageView) view.findViewById(R.id.userSetIcon);
        userSetIcon.setOnClickListener(this);

        userImage = (ImageView) view.findViewById(R.id.userIcon);
        userImage.setOnClickListener(this);

        userIntro = (TextView) view.findViewById(R.id.userIntro);

        userName = (TextView) view.findViewById(R.id.userName);

        careId = (TextView) view.findViewById(R.id.careId);
        funsId = (TextView) view.findViewById(R.id.funsId);
        dynamicsId = (TextView) view.findViewById(R.id.dynamicsId);


        userSet = (ImageView) view.findViewById(R.id.userSet);
        userSet.setOnClickListener(this);
/*
        updateUser = (TextView) view.findViewById(R.id.updateUser);
        updateUser.setOnClickListener(this);
*/

        userHeight = (TextView) view.findViewById(R.id.heighData);
        userHeight.setOnClickListener(this);

        userWeight = (TextView) view.findViewById(R.id.weightData);
        userWeight.setOnClickListener(this);

        userBMI = (TextView) view.findViewById(R.id.bmiData);
        userBMI.setOnClickListener(this);

        gradePlan = (TextView) view.findViewById(R.id.gradePlan);

        gradeProgressd = (ImageView) view.findViewById(R.id.gradeProgressd);
        gradeProgress = (ImageView) view.findViewById(R.id.gradeProgress);
        para = gradeProgress.getLayoutParams();

        getStart = (TextView) view.findViewById(R.id.getStart);
        getStart.setOnClickListener(this);

        recyclerView = (RecyclerView) view.findViewById(R.id.photoRecyclerView);
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.HORIZONTAL));
        //获取用户的今日运动距离
        // getOneSport(user.userId, getNowDate());

        //获取用户的当月累计运动距离
       // getDis(user.userId);

        sportSucces = (LinearLayout) view.findViewById(R.id.sportSucces);
        sportSucces.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context,Li_Medal_Activity.class);
                intent.putExtra("dis",dis);
                startActivity(intent);
            }
        });

    }

    @Override
    public void initData() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.userImage:
                goUserInfo();
                break;
            case R.id.userSetIcon:
                goUserInfo();
                break;
/*            case userName:
                goUserInfo();
                break;*/
            case R.id.userSet:
                userSet();
                break;
          /*  case R.id.updateUser:
                goUserInfo();
                break;*/
            case R.id.heighData:
                goUserInfo();
                break;
            case R.id.weightData:
                goUserInfo();
                break;
            case R.id.bmiData:
                goUserInfo();
                break;
           /* case R.id.getStart:
                Toast.makeText(context,"1111",Toast.LENGTH_SHORT).show();
                break;*/
        }
    }

    /**
     * 跳转到个人详情页面
     */
    public void goUserInfo() {
        Intent intent = new Intent(context, UpdateUserActivity.class);
        startActivity(intent);
    }

    /**
     * 跳转到设置界面
     */
    public void userSet() {
        Intent intent = new Intent(context, SetActivity.class);
        startActivity(intent);
    }


    //获取网络数据
    public void getUserInfo(){
        Call<Li_UserInfoResult> call = MyModel.getModel().getService().getUserInfo(UserBean.getUserBean().userId, UserBean.getUserBean().userId);

        call.enqueue(new Callback<Li_UserInfoResult>() {
            @Override
            public void onResponse(Call<Li_UserInfoResult> call, Response<Li_UserInfoResult> response) {
                if (response.isSuccessful()) {
                    Li_UserInfoResult result = response.body();
                    if (result.getCode() == 0) {
                        updateView(result);

                    } else {

                    }
                }
            }

            @Override
            public void onFailure(Call<Li_UserInfoResult> call, Throwable t) {

            }
        });
    }

    //修改界面
    public void updateView(Li_UserInfoResult result){

        if(result.getData().getHumorlist().size() > 0){
            if(result.getData().getHumorlist().get(0).getHumorImgUrl() == null || result.getData().getHumorlist().get(0).getHumorImgUrl() == ""){

            }else{
                //获取图片
                String[] img = null;
                int n = 0;
                for (int i = 0; i < result.getData().getHumorlist().size(); i++) {
                    if (result.getData().getHumorlist().get(i).getHumorImgUrl().split(",") != null) {
                        img = result.getData().getHumorlist().get(i).getHumorImgUrl().split(",");
                        n = i;
                        break;
                    }
                }
                for (int i = n + 1; i < result.getData().getHumorlist().size(); i++) {
                    img = concat(img, result.getData().getHumorlist().get(i).getHumorImgUrl().split(","));
                }


                adapter = new RecyclerUserPicAdapter(context,img);
                recyclerView.setAdapter(adapter);
            }
        }


        careId.setText(result.getData().getCares()+"");
        funsId.setText(result.getData().getFanscount()+"");
        dynamicsId.setText(result.getData().getExtra().getTotalSize()+"");

        gradePlan.setText(String.valueOf(result.getData().getCountSport()));
        mCache.put("alldis",result.getData().getCountSport());
        dis = result.getData().getCountSport();
        //计算用户的跑步等级
        getGrade(result.getData().getCountSport(),gradeProgressd.getWidth());


        adapter.setOnItemClickListener(new RecyclerUserPicAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view) {

            }

            @Override
            public void onItemLongClick(View view) {

            }
        });
    }

    /**
     * 数组合并
     *
     * @return
     */
    static String[] concat(String[] a, String[] b) {
        String[] c = new String[a.length + b.length];
        return c;
    }

    //计算等级
    public void getGrade(int countSport,int width){
        if(countSport < 20){
            para.width = (int)(((((float)countSport/20)/4)) * width);
        }else if(countSport>= 20 && countSport < 50){
            para.width = (int)(((((float)(countSport-20)/30)/4 + 1/4)) * width);
        }else if(countSport>= 50 && countSport < 200){
            para.width = (int)(((((float)(countSport - 50)/150)/4 + 1/2)) * width);
        }else if(countSport>= 200 && countSport < 500){
            para.width = (int)(((((float)(countSport - 200)/300)/4 + 3/4)) * width);
        }else if(countSport>= 500 && countSport < 2000){
            para.width = width;
        }
        //设置等级进度条
        gradeProgress.setLayoutParams(para);
    }

    /**
     * 从服务器获取距离
     */
    /*public void getDis(int userId) {
        Call<RegistResult> call = GetDisModel.getModel().getService().getResult(Default.countDis, userId);

        call.enqueue(new Callback<RegistResult>() {
            @Override
            public void onResponse(Call<RegistResult> call, Response<RegistResult> response) {
                if (response.isSuccessful()) {
                    RegistResult result = response.body();
                    if (result.getNum() != -1) {

                        dis = result.getNum();
                        //设置运动成就
                        Log.i("运动距离", dis + "===========");
                        setSuccess(dis);

                        //设置等级经度条进度
                        ObjectAnimator.ofFloat(overImageView, "translationX", w * ((float) 20/100)).setDuration(500).start();

                    } else {

                    }
                }
            }

            @Override
            public void onFailure(Call<RegistResult> call, Throwable t) {

            }
        });
    }*/

    /**
     * 获取系统当前日期
     *
     * @return
     */
    public String getNowDate() {
        Date dt = new Date();
        SimpleDateFormat matter1 = new SimpleDateFormat("yyyy.MM.dd");
        String dateStr = matter1.format(dt);
        Log.i("当前时间", dateStr);
        return dateStr;
    }

    /**
     * 根据用户的累计运动距离设置运动成就
     */
    public void setSuccess(int distance) {

        /**
         * 因为没有图片，暂时先注释了
         */
        /*if(distance >= 3 && distance <5){
			Picasso.with(context)
					.load(R.mipmap.ic_launcher)
					.into(successImage);
			successText.setText("3公里成就");
		}else if(distance >= 5 && distance <10){
			Picasso.with(context)
					.load(R.mipmap.ic_launcher)
					.into(successImage);
			successText.setText("5公里成就");
		}else if(distance >= 10 && distance <21){
			Picasso.with(context)
					.load(R.mipmap.ic_launcher)
					.into(successImage);
			successText.setText("10公里成就");
		}else if(distance >= 21 && distance <42){
			Picasso.with(context)
					.load(R.mipmap.ic_launcher)
					.into(successImage);
			successText.setText("21公里成就");
		}else if(distance >= 42 && distance <50){
			Picasso.with(context)
					.load(R.mipmap.ic_launcher)
					.into(successImage);
			successText.setText("42公里成就");
		}else if(distance >= 50 && distance <100){
			Picasso.with(context)
					.load(R.mipmap.ic_launcher)
					.into(successImage);
			successText.setText("50公里成就");
		}else if(distance >= 100){
			Picasso.with(context)
					.load(R.mipmap.ic_launcher)
					.into(successImage);
			successText.setText("100公里成就");
		}*/
    }

/*	//接口回调
	public interface OnGetPro {
		public void getPro(int pro);
		public void shareSport(String text,String title,String url,String media);
	}*/

    OnGetPro mListener;

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        //在onAttach方法中实例化myListener
        mListener = (OnGetPro) activity;
    }

   /* @OnClick(R.id.addNotes)
    public void onClick() {
        Intent intent = new Intent(context, AddThemeActivity.class);
        startActivity(intent);
    }*/
}
